﻿namespace EasyToolkit.Excel.ContextualMenus.Definition
{
    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;
    using EasyToolkit.Tools.Extensions;

    [XmlRoot("ContextualMenu") ]
    public class XmlContextualMenuDefinition : XmlContextualMenuPart
    {
        [XmlAttribute]
        public string Name
        { get; set; }

        [XmlAttribute]
        public string Caption
        { get; set; }

        [XmlAttribute]
        public string InsertBefore
        { get; set; }

        [XmlAttribute]
        public bool BeginGroup
        { get; set; }

        [XmlElement(ElementName = "MenuItem", Type = typeof(XmlContextualMenuItemDefinition))]
        [XmlElement(ElementName = "ContextualMenu", Type = typeof(XmlContextualMenuDefinition))]
        public List<XmlContextualMenuPart> Items
        { get; set; }

        static public XmlContextualMenuDefinition CreateInstance(string definition)
        {
            XmlContextualMenuDefinition ret = null;
            definition = definition.EmptyIfNull().Trim();
            if (! string.IsNullOrEmpty(definition))
            {
                try
                {
                    ret = definition.Deserialize<XmlContextualMenuDefinition>();
                }
                catch (Exception ex)
                {
                    string message = string.Format("Cannot retrieve the contextual menu definition. {0}", ex.Message);
                    throw new EasyToolkitException(message, ex);
                }
            }
            return ret;
        }
    }
}
